<template>
  <div class="id-card-processing" style="font-family:Simsun">
    <el-card style="width: 70%; margin: 0 auto;">
      <h2>居住证办理</h2>
      <el-row :gutter="20" class="input-row">
        <el-col :span="12">

          <el-form-item label="请输入身份证号码" style="flex: 1 0 33%;">
            <el-input v-model="idNumber" placeholder="请输入身份证号" ></el-input>
          </el-form-item>

        </el-col>
        <el-col :span="8">
          <el-button type="primary" @click="query">查询</el-button>
        </el-col>
      </el-row>

      <el-row :gutter="20" class="info-row">
        <el-col :span="12">
          <el-form :model="detailData" label-width="100px">
            <el-form-item label="姓名*" style="flex: 1 0 33%;">
              <el-input v-model="detailData.name" :disabled="true" />
            </el-form-item>
            <el-form-item label="性别*" style="flex: 1 0 33%;">
              <el-input v-model="detailData.gender" :disabled="true" />
            </el-form-item>
            <el-form-item label="民族*" style="flex: 1 0 33%;">
              <el-input v-model="detailData.ethnicity" :disabled="true" />
            </el-form-item>
            <el-form-item label="出生日期*" style="flex: 1 0 33%;">
              <el-input v-model="detailData.birthDate" :disabled="true" />
            </el-form-item>
            <el-form-item label="户籍地址*" style="flex: 1 0 33%;">
              <el-input v-model="detailData.household.registeredAddress" :disabled="true" />
            </el-form-item>
            <el-form-item label="现地址*" style="flex: 1 0 33%;">
              <el-input v-model="detailData.migrantPopulation.currentAddress" :disabled="true" />
            </el-form-item>
            <el-form-item label="身份证号*" style="flex: 1 0 33%;">
              <el-input v-model="detailData.idNumber" :disabled="true" />
            </el-form-item>
            <el-form-item label="签发机关*" style="flex: 1 0 33%;" v-if="detailData.policeStation">
              <el-input v-model="detailData.policeStation.name" :disabled="true" />
            </el-form-item>
            <el-form-item label="有效期限*" style="flex: 1 0 33%;">
              <el-input v-model="detailData.idCardStatus.expiryDate" :disabled="true" />
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="12" class="upload-container">
          <div>
            <el-upload
              ref="upload"
              class="upload-demo"
              v-model:file-list="fileList"
              drag
              action="http://localhost:9000/certificate/id/manage/upload"
              list-type="picture-card"
              :limit="1"
              :disabled="disabled"
              :before-upload="beforeAvatarUpload"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
              :on-success="handleSuccess"
            >
              <el-icon class="el-icon--upload"><upload-filled /></el-icon>
              <div class="el-upload__text">
                在此处上传证件照<em>点击上传</em>
              </div>
            </el-upload>
            <div>
              <el-dialog v-model="previewDialogVisible" width="50%">
                <img class="preview-image" :src="dialogImageUrl" alt="Preview Image" />
              </el-dialog>
            </div>
          </div>
        </el-col>
      </el-row>

      <div class="buttons">
        <el-button type="primary" @click="apply" :disabled="!canApply">申领</el-button>
        <el-button type="primary" @click="issue" :disabled="!canIssue">发证</el-button>
        <el-button type="primary" @click="reportLost" :disabled="!canReportLost">挂失</el-button>
        <el-button type="primary" @click="reissue" :disabled="!canReissue">作废</el-button>
      </div>

      <el-table :data="tableData" style="width: 100%; margin-top: 20px;">
        <el-table-column prop="idNumber" label="证号" align="center"></el-table-column>
        <el-table-column prop="name" label="姓名" align="center"></el-table-column>
        <el-table-column prop="idCardStatus.status" label="状态" align="center"></el-table-column>
        <el-table-column prop="idCardStatus.applicationDate" label="申领日期" align="center"></el-table-column>
        <el-table-column prop="idCardStatus.issueDate" label="发证日期" align="center"></el-table-column>
        <el-table-column prop="idCardStatus.lostDate" label="挂失日期" align="center"></el-table-column>
        <el-table-column prop="idCardStatus.invalidDate" label="作废日期" align="center"></el-table-column>
        <el-table-column label="操作" align="center">
          <template v-slot="scope">
            <el-button @click="showRecord(scope.row)" type="text" size="small">办理记录</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-dialog title="办理记录" v-model="dialogVisible">
      <el-table :data="recordData" style="width: 100%;">
        <el-table-column prop="businessType" label="办理业务"></el-table-column>
        <el-table-column prop="applicationDate" label="办理时间"></el-table-column>
        <el-table-column prop="policeStation.name" label="办理地点"></el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer" style="display: flex; justify-content: flex-end;">
        <el-button @click="dialogVisible = false">关闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script setup>
import { reactive, ref, computed } from "vue";
import { ElMessage } from 'element-plus'
import { useStore } from 'vuex';
import { searchResidenceCardStatusByIdNumber } from "@/api/epgms/certificate/residence/search";
import { updateResidenceCardStatus } from "@/api/epgms/certificate/residence/update";
import { searchResidenceCardRecords } from "@/api/epgms/certificate/residence/records";
import { addResidenceCardRecords } from "@/api/epgms/certificate/residence/add";

const tableData = reactive([]);
const dialogImageUrl = ref('');
const previewDialogVisible = ref(false);
const fileList = ref([]);
const disabled = ref(false);
const upload = ref();
const officerInfo= useStore().getters.officerInfo;

let detailData = ref({
  household: {
    registeredAddress: ''
  },
  policeStation: {
    name: ''
  },
  migrantPopulation:{
    currentAddress:'',
    residenceDuration: ''
  },
  idCardStatus:{
    statusId:'',
    businessType: '',
    policeStationId: '',
    cardType: '居住证',
    applicationDate: '',
    issueDate: '',
    lostDate: '',
    expiryDate: '',
    invalidDate: '',
    photoUrl:'',
    status:''
  },
  name: '',
  gender: '',
  idNumber: '',
  birthDate: '',
  ethnicity: '',
  personId: '',
});

const idNumber = ref('');
const dialogVisible = ref(false);
const recordData = ref([]);


// 用于控制按钮启用和禁用的计算属性
let canApply = computed(() => detailData.value.idCardStatus.status === '作废'|| detailData.value.idCardStatus.status === '');
let canIssue = computed(() => detailData.value.idCardStatus.status === '申领' && detailData.value.idCardStatus.photoUrl);
let canReportLost = computed(() => detailData.value.idCardStatus.status === '正常');
let canReissue = computed(() => detailData.value.idCardStatus.status === '挂失');

const handlePictureCardPreview = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url;
  previewDialogVisible.value = true;
};

const handleRemove = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles);
};

const handleSuccess = (res)=>{
  console.log("message"+res.data)
  console.log("photoUrl___"+detailData.value.idCardStatus.photoUrl)
  detailData.value.idCardStatus.photoUrl=res.data
  console.log("photoUrl___"+detailData.value.idCardStatus.photoUrl)
}
const beforeAvatarUpload = (uploadFile) => {
  if (uploadFile.type !== 'image/jpeg' && uploadFile.type !== 'image/png') {
    ElMessage.error('Avatar picture must be JPG or PNG format!');
    return false;
  } else if (uploadFile.size / 1024 / 1024 > 0.5) {
    ElMessage.error('Avatar picture size can not exceed 500KB!');
    return false;
  }
  return true;
};

const fetchData = async () => {
  const res = await searchResidenceCardStatusByIdNumber({
    idNumber: idNumber.value
  });
  if (res.data.code === 2000 && res) {
    const person = res.data.data;
    if (person.migrantPopulation==null)
    {
      detailData.value=null
      return;
    }
    tableData.splice(0,tableData.length,res.data.data);
    detailData.value = person;
    detailData.value.idCardStatus = person.idCardStatus || {
      statusId: '',
      businessType: '',
      policeStationId: '',
      cardType: '居住证',
      applicationDate: '',
      issueDate: '',
      lostDate: '',
      expiryDate: '',
      invalidDate: '',
      photoUrl: '',
      status: ''
    };

    if (person.idCardStatus && person.idCardStatus.photoUrl) {
      fileList.value = [{
        name: detailData.value.name + ".jpg",
        url: person.idCardStatus.photoUrl
      }];
    } else {
      fileList.value = [];
    }

  } else {
    ElMessage.error('未找到匹配的记录');
  }
};

const query = async () => {
  if (!idNumber.value) {
    ElMessage.error('请输入身份证号');
    return;
  }
  const res = await searchResidenceCardStatusByIdNumber({
    idNumber: idNumber.value
  });
  if (res.data.code === 2000 && res) {
    const person = res.data.data
    if (person.migrantPopulation==null)
    {
      ElMessage.error('仅流动人口可以办理居住证！');
      await fetchData()
      return;
    }
    tableData.splice(0,tableData.length,res.data.data);
    detailData.value = person;
    detailData.value.idCardStatus = person.idCardStatus || {
      statusId: '',
      businessType: '',
      policeStationId: '',
      cardType: '居住证',
      applicationDate: '',
      issueDate: '',
      lostDate: '',
      expiryDate: '',
      invalidDate: '',
      photoUrl: '',
      status: ''
    };
    if (person.idCardStatus && person.idCardStatus.photoUrl) {
      fileList.value = [{
        name: detailData.value.name + ".jpg",
        url: person.idCardStatus.photoUrl
      }];
    } else {
      fileList.value = [];
    }
  } else {
    ElMessage.error('未找到匹配的记录');
  }
};

const apply = async () => {
  if (!detailData.value.idCardStatus.photoUrl) {
    ElMessage.error('请上传照片');
    return;
  }
  detailData.value.idCardStatus.status = '申领';
  detailData.value.idCardStatus.applicationDate = nowDate(0);
  detailData.value.idCardStatus.expiryDate = `${nowDate(0)}-${nowDate(detailData.value.migrantPopulation.residenceDuration)}`;
  detailData.value.idCardStatus.policeStationId = officerInfo.policeStation.stationId;
  try {
    const response = await updateResidenceCardStatus({
      personId: detailData.value.personId,
      statusId: detailData.value.idCardStatus.statusId,
      cardType: detailData.value.idCardStatus.cardType,
      applicationDate: detailData.value.idCardStatus.applicationDate,
      expiryDate: detailData.value.idCardStatus.expiryDate,
      photoUrl: detailData.value.idCardStatus.photoUrl,
      policeStationId: detailData.value.idCardStatus.policeStationId,
      status: detailData.value.idCardStatus.status
    });
    if (response.data.code === 2000 && response) {
      ElMessage.success('申领成功！');
      await fetchData();
      await addIdCardRecord('申领');
    } else {
      ElMessage.error('申领失败！');
    }
  } catch (error) {
    console.error("申领失败:", error);
    ElMessage.error('申领失败');
  }
};

const issue = async () => {
  detailData.value.idCardStatus.status = '正常';
  detailData.value.idCardStatus.issueDate = nowDate(0);

  try {
    const response = await updateResidenceCardStatus({
      personId: detailData.value.personId,
      statusId: detailData.value.idCardStatus.statusId,
      cardType: detailData.value.idCardStatus.cardType,
      issueDate: detailData.value.idCardStatus.issueDate,
      photoUrl: detailData.value.idCardStatus.photoUrl,
      status: detailData.value.idCardStatus.status
    });
    if (response.data.code === 2000 && response) {
      ElMessage.success('发证成功！');
      await fetchData();
      await addIdCardRecord('发证');
    } else {
      ElMessage.error('发证失败！');
    }
  } catch (error) {
    console.error("发证失败:", error);
    ElMessage.error('发证失败');
  }
};

const reportLost = async () => {
  detailData.value.idCardStatus.status = '挂失';
  detailData.value.idCardStatus.lostDate = nowDate(0);

  try {
    const response = await updateResidenceCardStatus({
      personId: detailData.value.personId,
      statusId: detailData.value.idCardStatus.statusId,
      cardType: detailData.value.idCardStatus.cardType,
      lostDate: detailData.value.idCardStatus.lostDate,
      photoUrl: detailData.value.idCardStatus.photoUrl,
      status: detailData.value.idCardStatus.status
    });
    if (response.data.code === 2000 && response) {
      ElMessage.success('挂失成功！');
      await fetchData();
      await addIdCardRecord('挂失');
    } else {
      ElMessage.error('挂失失败！');
    }
  } catch (error) {
    console.error("挂失失败:", error);
    ElMessage.error('挂失失败');
  }
};

const reissue = async () => {
  detailData.value.idCardStatus.status = '作废';
  detailData.value.idCardStatus.invalidDate = nowDate(0);
  console.log("statusId"+detailData.value.idCardStatus.cardType)
  try {
    const response = await updateResidenceCardStatus({
      personId: detailData.value.personId,
      statusId: detailData.value.idCardStatus.statusId,
      cardType: detailData.value.idCardStatus.cardType,
      invalidDate: detailData.value.idCardStatus.invalidDate,
      photoUrl: detailData.value.idCardStatus.photoUrl,
      status: detailData.value.idCardStatus.status
    });
    if (response.data.code === 2000 && response) {
      ElMessage.success('作废成功！');
      await fetchData();
      await addIdCardRecord('作废');
    } else {
      ElMessage.error('作废失败！');
    }
  } catch (error) {
    console.error("作废失败:", error);
    ElMessage.error('作废失败');
  }
};

const showRecord = async (row) => {
  const res = await searchResidenceCardRecords({
    personId: row.personId
  });
  if (res.data.code === 2000 && res) {
    recordData.value = res.data.data
    dialogVisible.value = true;
  } else {
    ElMessage.error('未找到匹配的记录');
  }
};

const addIdCardRecord = async (businessType) => {
  let applicationDate =''
  switch (businessType) {
    case "申领":applicationDate=detailData.value.idCardStatus.applicationDate
      break;
    case "发证":applicationDate=detailData.value.idCardStatus.issueDate
      break;
    case "挂失":applicationDate=detailData.value.idCardStatus.lostDate
      break;
    case "作废":applicationDate=detailData.value.idCardStatus.invalidDate
      break;
    default :console.log("业务类型不存在")
  }
  const res = await addResidenceCardRecords({
    personId: detailData.value.personId,
    cardType: detailData.value.idCardStatus.cardType,
    applicationDate: applicationDate,
    policeStationId: officerInfo.policeStation.stationId,
    businessType: businessType
  });
  if (res.data.code === 2000 && res) {
    console.log("记录保存成功！");
  }
};

const nowDate = (length) => {
  const time = new Date();
  const year = time.getFullYear() + length;
  const month = (time.getMonth() + 1).toString().padStart(2, '0');
  const date = time.getDate().toString().padStart(2, '0');
  return `${year}.${month}.${date}`;
};
</script>

<style scoped>
.input-row,
.info-row {
  margin-bottom: 20px;
}

.upload-container {
  text-align: center;
}

.buttons {
  text-align: center;
  margin-top: 20px;
}


.upload-demo .el-upload__input {
  display: none;
  height: 200px;

}

.preview-image {
  width: 80%;
}
::v-deep .element.style{
  padding-top: 100px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style>
